package com.gxuwz.bignews.view.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Button;
import android.widget.ImageView;
import android.content.pm.PackageManager;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.gxuwz.bignews.MainActivity;
import com.gxuwz.bignews.R;

public class SplashAdActivity extends AppCompatActivity {
    private ImageView adImage;
    private Button btnSkip;
    private Handler handler = new Handler();
    private int countdown = 30; // 30秒倒计时
    private int currentAdIndex = 0;
    // 简单广告数据：图片资源（移除了ad3）
    private int[] adImages = {R.drawable.ad1, R.drawable.ad2};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_ad);

        adImage = findViewById(R.id.ad_image);
        btnSkip = findViewById(R.id.btn_skip);

        showAd(currentAdIndex);
        startAdLoop();
        startCountdown();

        adImage.setOnClickListener(v -> onAdClick());
        btnSkip.setOnClickListener(v -> goToLogin());
    }

    private void showAd(int index) {
        adImage.setImageResource(adImages[index]);
    }

    private void startAdLoop() {
        handler.postDelayed(() -> {
            currentAdIndex = (currentAdIndex + 1) % adImages.length;
            showAd(currentAdIndex);
            startAdLoop();
        }, 2000); // 2秒切换一张
    }

    private void startCountdown() {
        btnSkip.setText("跳过(" + countdown + ")");
        handler.postDelayed(() -> {
            countdown--;
            if (countdown > 0) {
                startCountdown();
            } else {
                goToLogin();
            }
        }, 1000);
    }

    private void goToLogin() {
        handler.removeCallbacksAndMessages(null);
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }

    private void onAdClick() {
        // 无论是哪张广告，都尝试跳转到拼多多应用
        try {
            Intent intent = new Intent();
            intent.setPackage("com.xunmeng.pinduoduo");
            intent.setAction(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            startActivity(intent);
        } catch (Exception e) {
            // 如果没有安装拼多多应用，则尝试打开应用商店下载页
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse("market://details?id=com.xunmeng.pinduoduo"));
                startActivity(intent);
            } catch (Exception e1) {
                // 如果没有应用商店，则尝试打开拼多多网页
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse("https://mobile.yangkeduo.com/"));
                startActivity(intent);
            }
        }
    }
} 